package com.financial.business.integral.service.yd.impl;

import com.financial.business.integral.config.UrlConfig;
import com.financial.business.integral.connector.SysconfigFeign;
import com.financial.business.integral.constants.FinancialIntegralEnumConstants;
import com.financial.business.integral.constants.FinancialPayIntegralEnumConstants;
import com.financial.business.integral.dao.FinancialYDPayIntegralDao;
import com.financial.business.integral.domain.FinancialYDPayIntegralDO;
import com.financial.business.integral.dto.FinancialYDIntegralDTO;
import com.financial.business.integral.service.yd.FinancialYDIntegralPayService;
import com.financial.business.integral.utils.HttpClientUtils;
import com.financial.business.integral.utils.JsonUtils;
import com.financial.business.integral.utils.RedisUtils;
import com.financial.business.integral.utils.ValidateUtils;
import com.financial.business.integral.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //优店积分支付查询接口
 * @Date 2019/12/6 17:05
 */
@Service
public class FinancialYDIntegralPayServiceImpl implements FinancialYDIntegralPayService {
    public static final Logger logger = LoggerFactory.getLogger(FinancialYDIntegralPayServiceImpl.class);

    @Autowired
    private FinancialYDPayIntegralDao financialYDPayIntegralDao;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Override
    public ApiResult pay(String requestParam) {
        logger.info("FinancialYDIntegralPayServiceImpl.pay---接收支付信息json格式:" + requestParam);
        FinancialYDIntegralDTO financialYDIntegralDTO = JsonUtils.convertBean(requestParam, FinancialYDIntegralDTO.class);
        Map<String, Object> params = JsonUtils.jsonToMap(requestParam);
        /*支付金额*/
        Object tempParam = params.get("total_amount");
        String totalAmountStr = tempParam == null ? null : tempParam.toString();
        /*三方支付专用的交易单号*/
        tempParam = params.get("out_trade_no");
        String outTradeNo = tempParam == null ? null : tempParam.toString();
        /*商品的标题*/
        tempParam = params.get("subject");
        String subject = tempParam == null ? null : tempParam.toString();
        /*支付类型*/
        tempParam = params.get("pay_type");
        String payType = tempParam == null ? null : tempParam.toString();
        /*对接平台商户号*/
        tempParam = params.get("store_no");
        String storeNo = tempParam == null ? null : tempParam.toString();
        /*平台支付单号*/
        tempParam = params.get("pay_id");
        String payId = tempParam == null ? null : tempParam.toString();
        /*支付通道费用*/
        tempParam = params.get("pay_fee");
        String payFeeStr = tempParam == null ? null : tempParam.toString();
        /*回执地址*/
        tempParam = params.get("notify_url");
        String notifyUrl = tempParam == null ? null : tempParam.toString();
        /*商户编码*/
        tempParam = params.get("customer_no");
        String customerNo = tempParam == null ? null : tempParam.toString();
        /*业务类型*/
        tempParam = params.get("business_type");
        String businessType = tempParam == null ? null : tempParam.toString();
        /*现在支付渠道类型编码*/
        tempParam = params.get("pay_channel_no");
        String payChannelNo = tempParam == null ? null : tempParam.toString();
        /*对接平台编码*/
        tempParam = params.get("platform_no");
        String platformNo = tempParam == null ? null : tempParam.toString();
        /*获取收取认证*/
        tempParam = params.get("authorization");
        String authorization = tempParam == null ? null : tempParam.toString();
        if (StringUtils.isBlank(totalAmountStr) || StringUtils.isBlank(outTradeNo)
                || StringUtils.isBlank(subject) || StringUtils.isBlank(payType)
                || StringUtils.isBlank(customerNo) || StringUtils.isBlank(storeNo)
                || StringUtils.isBlank(payId) || StringUtils.isBlank(payFeeStr)
                || StringUtils.isBlank(notifyUrl) || StringUtils.isBlank(businessType)
                || StringUtils.isBlank(platformNo) || StringUtils.isBlank(payChannelNo)
                || StringUtils.isBlank(authorization)) {
            /*对所传字段进行非空校验判断*/
            logger.info("FinancialYDIntegralPayServiceImpl.pay---金融中心积分支付信息校验是否为空:" + ValidateUtils.validateProperty(financialYDIntegralDTO));
            return ApiResult.failure(ValidateUtils.validateProperty(financialYDIntegralDTO));
        }
        try {
            redisUtils.setKey(outTradeNo, authorization, 60 * 30);
            /*获取够样支付平台信息*/
            ApiResult apiResult = sysconfigFeign.platfromInfo(payChannelNo);
            String apiResultMsg = (String) apiResult.getResult();
            if (apiResult.getCode() == FinancialPayIntegralEnumConstants.ENUM_CODE_SUC || (apiResultMsg != null && apiResultMsg != "")) {
                /*获取每个参数信息*/
                Map<String, Object> map = JsonUtils.jsonToMap(apiResultMsg);
                String platfromNo = (String) map.get("platfrom_no");
                /*对分账所有的金额进行精确度设置，保留两位小数*/
                /*支付总金额*/
                BigDecimal totalAmount = new BigDecimal(totalAmountStr).setScale(2, RoundingMode.HALF_UP);
                /*手续费金额*/
                BigDecimal payFee = new BigDecimal(payFeeStr).setScale(2, RoundingMode.HALF_UP);
                /*保存数据初始化*/
                FinancialYDPayIntegralDO financialYDPayIntegralDO = new FinancialYDPayIntegralDO();
                financialYDPayIntegralDO.setGmtCreate(new Date());
                financialYDPayIntegralDO.setGmtModified(new Date());
                financialYDPayIntegralDO.setIsDelete(FinancialIntegralEnumConstants.ENUM_ISDELETE_UNDEL);
                financialYDPayIntegralDO.setCustomerId(customerNo);
                financialYDPayIntegralDO.setOutTradeNo(outTradeNo);
                financialYDPayIntegralDO.setPayId(payId);
                financialYDPayIntegralDO.setPayFee(payFee);
                financialYDPayIntegralDO.setPayType(payType);
                financialYDPayIntegralDO.setPlatformNo(platformNo);
                financialYDPayIntegralDO.setResqContent(requestParam);
                financialYDPayIntegralDO.setTotalAmount(totalAmount);
                financialYDPayIntegralDO.setStoreNo(storeNo);
                financialYDPayIntegralDO.setState(FinancialPayIntegralEnumConstants.ENUM_STATE_WAIT);
                financialYDPayIntegralDO.setReturnMessage(FinancialPayIntegralEnumConstants.ENUM_RETURNMESSAGE_FAIL);
                int res = financialYDPayIntegralDao.save(financialYDPayIntegralDO);
                if (res > 0) {
                    logger.info("FinancialYDIntegralPayServiceImpl.pay()-----保存金融中心数据信息成功！");
                    /*拼接请求参数对接够样平台*/
                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("customerId", customerNo);
                    requestMap.put("orderNum", outTradeNo);
                    requestMap.put("payCurrency", totalAmount);
                    requestMap.put("platformBusnum", platfromNo);
                    Map<String, String> condMap = new HashMap<>();
                    condMap.put("Authorization", authorization);
                    //余额平台回调地址
                    logger.info("FinancialYDIntegralPayServiceImpl.pay()-----拼接请求参数对接优店平台:" + JsonUtils.objectToJson(requestMap));
                    String result = httpClientUtils.doPostToJson(UrlConfig.INTEGRAL_YD_PREPAY_URL, requestMap, condMap);
                    Map<String, Object> resultMap = JsonUtils.jsonToMap(result);
                    /*更改数据库状态*/
                    Map<String, Object> updateMap = new HashMap();
                    updateMap.put("outTradeNo", outTradeNo);
                    updateMap.put("gmtModified", new Date());
                    updateMap.put("returnMessage", result);
                    if (!FinancialPayIntegralEnumConstants.ENUM_YDRETURNCODE_SUC.equals(resultMap.get("return_code"))) {
                        updateMap.put("state", FinancialPayIntegralEnumConstants.ENUM_STATE_FAIL);
                        financialYDPayIntegralDao.updateInfo(updateMap);
                        return ApiResult.failure("预支付单获取失败");
                    }
                    logger.info("FinancialYDIntegralPayServiceImpl.pay()-----积分预支付信息结果:" + requestMap.get("customerUuid") + "---" + JsonUtils.jsonToMap(result));
                    String prePayInfoMsg = resultMap.get("prePayInfoDO").toString();
                    updateMap.put("state", FinancialPayIntegralEnumConstants.ENUM_STATE_SUC);
                    financialYDPayIntegralDao.updateInfo(updateMap);
                    /*返回信息给调用端*/
                    logger.info("FinancialYDIntegralPayServiceImpl.pay()-----返回信息给调用端:" + prePayInfoMsg);
                    return ApiResult.success(prePayInfoMsg);
                } else {
                    logger.info("FinancialYDIntegralPayServiceImpl.pay()-----保存金融中心数据信息失败！");
                    return ApiResult.failure(requestParam);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialYDIntegralPayServiceImpl.pay()-----金融中心数据信息失败:" + e.getMessage());
        }
        return ApiResult.failure(requestParam);
    }

    @Override
    public String query(Map<String, Object> paramMap) {

        return financialYDPayIntegralDao.query(paramMap);
    }
}
